//
//  ViewController.m
//  ideashareDemo
//
//  Created by huawei on 2021/1/20.
//  Copyright © 2021 huawei. All rights reserved.
//

#import "ViewController.h"
#import <IdeaShare_SDK/IdeaShareServiceController.h>
#import <IdeaShare_SDK/IdeaShareDef.h>
#import <objc/runtime.h>
#import <ReplayKit/ReplayKit.h>
#import "AppDelegate.h"
#import "MeetControlViewController.h"
#import <CocoaLumberjack/CocoaLumberjack.h>

static DDLogLevel ddLogLevel = DDLogLevelInfo;
static ViewController * selfClass = nil;
extern BOOL inMeeting;
BOOL isSharing;
BOOL isConnected;
MeetControlViewController *meetControlVC;
NSUserDefaults *userDefault;
struct Audio_RTP_Header
{
    uint16_t bitDian;
    uint16_t usSeq;
    uint32_t ulTimestamp;
    uint32_t usSsrc;
} audio_RTP_Header = {0};

@interface ViewController ()
@property NSString *preCode;
@property UITextField *projectionNum;
@property UITextField *projectionIP;
@property UITextField *projectionPort;
@property IdeaShareServiceController *mShareController;
@property IdeaShareServiceAppInfo *appInfo;
@property IdeaShareServiceLogInfo *logInfo;
@property NSString * ip;
@property int port;
@property UIButton *meetControlBtn;
@property UIButton *shareControlBtn;
@property UIButton *connectBtn;
@property UISwitch *audioSwitch;
@property UILabel *deviceNameLbl;
@property UILabel *logLevelLbl;
@property UIButton *logDebugBtn;
@property UIButton *logInfoBtn;
@property UIButton *logWarningBtn;
@property UIButton *logErrorBtn;
@property (nonatomic,copy)NSString *timerName;
@property SharePolicy * policy;
@end

@implementation ViewController
- (void)dealloc {
    CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();
    CFNotificationCenterRemoveObserver(notification, (__bridge const void *)(self), CFSTR("writeMyLog"), NULL);
    CFNotificationCenterRemoveObserver(notification, (__bridge const void *)(self), CFSTR("extension_setup_info"), NULL);
    CFNotificationCenterRemoveObserver(notification, (__bridge const void *)(self), CFSTR("extension_stop_info"), NULL);
}
- (void)viewDidLoad {
    
    [super viewDidLoad];

    /* init video and audio data channel */
    [self initDDLog];
    
    [self registerNotification];
    /* setup UI */
    [self setupUI];
    selfClass = self;
}

- (void)initDDLog {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *baseDir = paths.firstObject;
    NSString *logsDirectory = [baseDir stringByAppendingPathComponent:@"Logs"];
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    DDLogFileManagerDefault * defualtFileManager = [[DDLogFileManagerDefault alloc]initWithLogsDirectory:logsDirectory];
    DDFileLogger *fileLogger = [[DDFileLogger alloc]initWithLogFileManager:defualtFileManager];
    fileLogger.rollingFrequency = 60*60*24;
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];
    DDLogInfo(@"DDLog Start Here");
}
- (void)registerNotification {
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), writeMyLogMethod,CFSTR("writeMyLog"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), extensionStartedWithSetupInfo,CFSTR("extension_setup_info"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), extensionStop,CFSTR("extension_stop_info"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    //注册耳机拔插监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(audioRouteChangeCallBack:) name:AVAudioSessionRouteChangeNotification object:nil];
}
void writeMyLogMethod (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    NSUserDefaults *userDefault = [[NSUserDefaults alloc]initWithSuiteName:kGroup];
    NSString *logText = [userDefault objectForKey:@"writeMyLogKey"];
    
    if (logText != nil) {
        DDLogInfo(@"扩展进程：%@", logText);
    }
}
    
- (void)setupUI {
    isSharing = NO;
    CGFloat viewWidth = self.view.frame.size.width;
    CGFloat viewHeight = self.view.frame.size.height;
    //初始化会控界面
    meetControlVC = [[MeetControlViewController alloc]init];
    //获取单例
    _mShareController = [IdeaShareServiceController shareInstance];
    [_mShareController initDataBuffer:kGroup];
    _mShareController.notifyDelegate = self;
    _appInfo = [[IdeaShareServiceAppInfo alloc]init];
    _logInfo = [[IdeaShareServiceLogInfo alloc]init];
    _logInfo.enable = true;
    _logInfo.logLevel = 3;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *baseDir = paths.firstObject;
    NSString *logsDirectory = [baseDir stringByAppendingPathComponent:@"Logs"];
    _logInfo.path = logsDirectory;
    [_mShareController setLog:_logInfo];
    [_mShareController create:_appInfo];
    _policy = [[SharePolicy alloc]init];
    _policy.isShareAudio = YES;
    _policy.isCompatibility = YES;
    [_mShareController setPolicy:_policy];
    _ip = @"";
    _port = 0;
    
    //1.设置界面背景色
    self.view.backgroundColor = [UIColor whiteColor];
    //2.提示栏
    UILabel *msgLbl = [[UILabel alloc] initWithFrame:CGRectMake((Screen_Width-150)/2, viewHeight/5, 150, 20)];
    msgLbl.text = @"请输入投屏码";
    msgLbl.font = [UIFont boldSystemFontOfSize:20];
    msgLbl.textColor = [UIColor blackColor];
    [self.view addSubview:msgLbl];
    
    //3.投屏码输入框
    _projectionNum = [[UITextField alloc] initWithFrame:CGRectMake((Screen_Width-150)/2, viewHeight/2-200, 150, 35)];
    _projectionNum.borderStyle = UITextBorderStyleRoundedRect;
    _projectionNum.clearButtonMode = UITextFieldViewModeAlways;
    _projectionNum.placeholder = @"投屏码";
    _projectionNum.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:_projectionNum];
    
    
    UILabel *tipLbl = [[UILabel alloc] initWithFrame:CGRectMake((Screen_Width-200)/2, viewHeight/2-150, 200, 35)];
    tipLbl.text = @"EUA模式请继续输入ip：";
    tipLbl.font = [UIFont boldSystemFontOfSize:15];
    tipLbl.textColor = [UIColor blackColor];
    [self.view addSubview:tipLbl];
    
    _projectionIP = [[UITextField alloc] initWithFrame:CGRectMake((Screen_Width-200)/2, viewHeight/2-100, 150, 35)];
    _projectionIP.borderStyle = UITextBorderStyleRoundedRect;
    _projectionIP.clearButtonMode = UITextFieldViewModeAlways;
    _projectionIP.placeholder = @"IP地址";
    _projectionIP.keyboardType = UIKeyboardTypeDecimalPad;
    [self.view addSubview:_projectionIP];
    
    _projectionPort = [[UITextField alloc] initWithFrame:CGRectMake((Screen_Width+100)/2, viewHeight/2-100, 80, 35)];
    _projectionPort.borderStyle = UITextBorderStyleRoundedRect;
    _projectionPort.clearButtonMode = UITextFieldViewModeAlways;
    _projectionPort.placeholder = @"端口";
    _projectionPort.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_projectionPort];
    
    //4.连接按钮
    isConnected = NO;
    _connectBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _connectBtn.frame = CGRectMake((Screen_Width-200)/2, viewHeight/2, 200, 40);
    //设置为圆角边框
    [_connectBtn.layer setMasksToBounds:YES];
    [_connectBtn.layer setCornerRadius:10.0];
    [_connectBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _connectBtn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    [_connectBtn setTitle:@"开始连接" forState:UIControlStateNormal];
    [_connectBtn addTarget:self action:@selector(connectClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_connectBtn];
    
    //6.版本号
    UILabel *versionLbl = [[UILabel alloc] init];
    versionLbl.frame = CGRectMake((viewWidth-200)/2, viewHeight-100, 200, 30);
    versionLbl.text = @"版本号：ideashare 10.0.2";
    versionLbl.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:versionLbl];
    
    //2.开始/停止共享按钮
    _shareControlBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _shareControlBtn.frame = CGRectMake((viewWidth-150)/2, viewHeight/2+100, 150, 40);
    _shareControlBtn.enabled = NO;
    //设置为圆角边框
    [_shareControlBtn.layer setMasksToBounds:YES];
    [_shareControlBtn.layer setCornerRadius:10.0];
    [_shareControlBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _shareControlBtn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    NSString *titleOfShareContlBtn = @"共享屏幕";
    //TODO 获取当前投屏状态
    BOOL shareState = NO;
    if(shareState){
        titleOfShareContlBtn = @"停止共享";
        _shareControlBtn.backgroundColor = [UIColor redColor];
    }
    [_shareControlBtn setTitle:titleOfShareContlBtn forState:UIControlStateNormal];
    [_shareControlBtn addTarget:self action:@selector(shareControl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_shareControlBtn];
    
    //6.共享音频开关
    UILabel *audioLbl = [[UILabel alloc] initWithFrame:CGRectMake((viewWidth-150)/2, viewHeight/2+150, 100, 35)];
    audioLbl.text = @"是否共享音频";
    audioLbl.font = [UIFont boldSystemFontOfSize:14];
    audioLbl.textColor = [UIColor blackColor];
    [self.view addSubview:audioLbl];
    
    _audioSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(viewWidth/2+30, viewHeight/2+150, 0, 0)];
    _audioSwitch.on = YES;
    [_audioSwitch addTarget:self action:@selector(audioSwitchChg:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_audioSwitch];
    
    //3.会议控制按钮
    _meetControlBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _meetControlBtn.frame = CGRectMake((viewWidth-150)/2, viewHeight/2+250, 150, 40);
    _meetControlBtn.enabled = NO;
    //设置为圆角边框
    [_meetControlBtn.layer setMasksToBounds:YES];
    [_meetControlBtn.layer setCornerRadius:10.0];
    [_meetControlBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _meetControlBtn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    [_meetControlBtn setTitle:@"会议控制" forState:UIControlStateNormal];
    [_meetControlBtn addTarget:self action:@selector(meetControl) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_meetControlBtn];
    
    //4.设备名显示
    _deviceNameLbl = [[UILabel alloc] initWithFrame:CGRectMake((Screen_Width-200)/2, viewHeight/2-50, 200, 35)];
    
    //5.当前日志级别显示
    _logLevelLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 150, 35)];
    NSString *Loglevel = @"";
    if(_logInfo.logLevel == 3) Loglevel = @"Debug";
    if(_logInfo.logLevel == 2) Loglevel = @"Info";
    if(_logInfo.logLevel == 1) Loglevel = @"Warning";
    if(_logInfo.logLevel == 0) Loglevel = @"Error";
    _logLevelLbl.text =[NSString stringWithFormat:@"当前日志级别为：%@", Loglevel];
    _logLevelLbl.font = [UIFont boldSystemFontOfSize:12];
    _logLevelLbl.textColor = [UIColor blackColor];
    [self.view addSubview:_logLevelLbl];
    
    //6.日志级别设置按钮
    _logDebugBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _logDebugBtn.frame = CGRectMake(170, 100, 50, 35);
    //设置为圆角边框
    [_logDebugBtn.layer setMasksToBounds:YES];
    [_logDebugBtn.layer setCornerRadius:10.0];
    [_logDebugBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _logDebugBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_logDebugBtn setTitle:@"Debug" forState:UIControlStateNormal];
    [_logDebugBtn addTarget:self action:@selector(logLevelControl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_logDebugBtn];
    
    _logInfoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _logInfoBtn.frame = CGRectMake(230, 100, 50, 35);
    //设置为圆角边框
    [_logInfoBtn.layer setMasksToBounds:YES];
    [_logInfoBtn.layer setCornerRadius:10.0];
    [_logInfoBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _logInfoBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_logInfoBtn setTitle:@"Info" forState:UIControlStateNormal];
    [_logInfoBtn addTarget:self action:@selector(logLevelControl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_logInfoBtn];
    
    _logWarningBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _logWarningBtn.frame = CGRectMake(290, 100, 60, 35);
    //设置为圆角边框
    [_logWarningBtn.layer setMasksToBounds:YES];
    [_logWarningBtn.layer setCornerRadius:10.0];
    [_logWarningBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _logWarningBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_logWarningBtn setTitle:@"Warning" forState:UIControlStateNormal];
    [_logWarningBtn addTarget:self action:@selector(logLevelControl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_logWarningBtn];
    
    _logErrorBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _logErrorBtn.frame = CGRectMake(360, 100, 50, 35);
    //设置为圆角边框
    [_logErrorBtn.layer setMasksToBounds:YES];
    [_logErrorBtn.layer setCornerRadius:10.0];
    [_logErrorBtn.layer setBorderWidth:1.0];
    //修改字体大小
    _logErrorBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_logErrorBtn setTitle:@"Error" forState:UIControlStateNormal];
    [_logErrorBtn addTarget:self action:@selector(logLevelControl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_logErrorBtn];
}

-(void)audioSwitchChg:(UISwitch*)audioSwitch{
    _policy.isShareAudio = audioSwitch.isOn ? YES : NO;
    DDLogInfo(@"共享音频开关修改为：%d",audioSwitch.isOn);
    [_mShareController setPolicy:_policy];
}
- (void)connectClick:(UIButton*)connectbtn
{
    if(!isConnected){
        //错误投屏码检验
        UIAlertController *errAlterControl = [UIAlertController alertControllerWithTitle:@"投屏码错误" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){}];
        //如果是ipad需要增加错误弹窗
        if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
            UIPopoverPresentationController *pop = [errAlterControl popoverPresentationController];
            pop.sourceView = self.view;//悬挂的视图
            pop.permittedArrowDirections = UIPopoverArrowDirectionUp;//箭头方向
            pop.sourceRect = self.view.bounds;//悬挂的地方
            pop.backgroundColor = [UIColor greenColor];
        }
        //长度超过限制
        if(_projectionNum.text.length>8){
            DDLogInfo(@"投屏码长度超过限制!!!!!!");
            errAlterControl.title = @"投屏码错误";
            errAlterControl.message = @"投屏码长度超过限制，请重新输入！";
            [errAlterControl addAction:defaultAction];
            [self presentViewController:errAlterControl animated:YES completion:^{
                        self->_projectionNum.text = @"";
                        self->_projectionIP.text = @"";
                        self->_projectionPort.text = @"";
            }];
            return;
        }
        //投屏码包含中文
        if([self hasChineese:_projectionNum.text]){
            DDLogInfo(@"投屏码中包含中文!!!!!!");
            errAlterControl.title = @"投屏码错误";
            errAlterControl.message = @"投屏码包含中文，请重新输入！";
            [errAlterControl addAction:defaultAction];
            [self presentViewController:errAlterControl animated:YES completion:^{
                        self->_projectionNum.text = @"";
                        self->_projectionIP.text = @"";
                        self->_projectionPort.text = @"";
            }];
            return;
        }
        
        [_mShareController discover:_projectionNum.text withAddress:_projectionIP.text withPort:[_projectionPort.text intValue] callback:^(id t) {
            DiscoverResult *discoverResult = (DiscoverResult*)t;
            NSMutableArray *address_list = discoverResult.address_list;
            NSString *password = discoverResult.password;
            int port = 1444;
             [self->_mShareController connect:address_list withPort:port withPassword:password callback:^(id t)
            {
                DDLogInfo(@"connect OK!!!!");
                dispatch_async(dispatch_get_main_queue(), ^{
                    self->_meetControlBtn.enabled = YES;
                    self->_shareControlBtn.enabled = YES;
                    isConnected = YES;
                    self->_projectionNum.text = @"";
                    self->_projectionIP.text = @"";
                    self->_projectionPort.text = @"";
                    // 切换按钮样式
                    [connectbtn setTitle:@"断开连接" forState:UIControlStateNormal];
                    connectbtn.backgroundColor = [UIColor redColor];
                    //  显示已连接设备
                    DeviceInfo *connectedDevice = (DeviceInfo *)t;
                    self->_deviceNameLbl.text = [[NSString alloc]initWithFormat:@"已连接设备：%@",connectedDevice.deviceName];
                    [self.view addSubview:self->_deviceNameLbl];
                });
            }];
        }];
    }
    else{
        if(isSharing){
            DDLogInfo(@"当前正在投屏，点击断开链接停止投屏！！！！");
            [self stopShare];
        }
        [_mShareController disconnect:^(id t){
            dispatch_async(dispatch_get_main_queue(), ^{
                self->_meetControlBtn.enabled = NO;
                self->_shareControlBtn.enabled = NO;
                isConnected = NO;
                
                // 切换按钮样式
                [connectbtn setTitle:@"开始连接" forState:UIControlStateNormal];
                connectbtn.backgroundColor = [UIColor whiteColor];
                // 移除已连接设备
                [self->_deviceNameLbl removeFromSuperview];
                
            });
        }];
    }
}

- (void) meetControl{
    DDLogInfo(@"用户点击会议控制按钮！！！！");
    [self.navigationController pushViewController:meetControlVC animated:YES];
}

//实现点击页面其他区域来收起键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)logLevelControl:(UIButton*)btn{
    int logLevel = -1;
    if([btn.titleLabel.text isEqual: @"Debug"])logLevel = 3; ddLogLevel = DDLogLevelDebug;
    if([btn.titleLabel.text isEqual: @"Info"]) logLevel = 2; ddLogLevel = DDLogLevelInfo;
    if([btn.titleLabel.text isEqual: @"Warning"]) logLevel = 1; ddLogLevel = DDLogLevelWarning;
    if([btn.titleLabel.text isEqual: @"Error"]) logLevel = 0; ddLogLevel = DDLogLevelError;
    _logInfo.logLevel = logLevel;
    [_mShareController setLog:_logInfo];
    [self initDDLog];
    _logLevelLbl.text = [NSString stringWithFormat:@"当前日志级别为：%@", btn.titleLabel.text];;
}

- (void)shareControl:(UIButton*)btn{
    if(isSharing){
        DDLogInfo(@"当前正在投屏，点击按钮停止投屏！！！！");
        [self stopShare];
        
    }else{
        // 视频采集
        _policy.isShareAudio = _audioSwitch.on;
        [_mShareController setPolicy:_policy];
        [self startCapture];
    }
}

- (void)startCapture {
    //系统自带弹框
    if (@available(iOS 12.0, *)) {
        RPSystemBroadcastPickerView * broadcastPickerView = [[RPSystemBroadcastPickerView alloc] initWithFrame:CGRectZero];
        broadcastPickerView.preferredExtension = REPLAY_EXTENSION_ID;
        broadcastPickerView.showsMicrophoneButton = NO;
        for (UIView *view in broadcastPickerView.subviews) {
            if ([view isKindOfClass:[UIButton class]]) {
                [(UIButton*)view sendActionsForControlEvents:UIControlEventAllTouchEvents];
            }
        }
    } else {
        // Fallback on earlier versions
    }
}

void extensionStartedWithSetupInfo (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    DDLogInfo(@"321 完成，建立通道！！！！");
    int shareRes = [selfClass -> _mShareController startSharing:^(id t){}];
    if(shareRes == 0){
        [selfClass -> _shareControlBtn setTitle:@"停止投屏" forState:UIControlStateNormal];
        selfClass -> _shareControlBtn.backgroundColor = [UIColor redColor];
        isSharing = YES;
        DDLogInfo(@"isshareing=:%d",isSharing);
    }
}

void extensionStop (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    DDLogInfo(@"extension停止投屏！！！！");
    if(isSharing == YES){
        [selfClass->_mShareController stopSharing:^(id t){}];
        dispatch_async(dispatch_get_main_queue(), ^{
            [selfClass->_shareControlBtn setTitle:@"共享屏幕" forState:UIControlStateNormal];
            selfClass->_shareControlBtn.backgroundColor = [UIColor whiteColor];
            isSharing = NO;
        });
    }
}

//notify 代理实现
- (void) onShareStatusChangeNotify : (IDEA_SHARE_APP_SERVER_STATUS) status : (IDEA_SHARE_APP_ERR) reason{
    DDLogInfo(@"收到共享状态变化的通知，状态为：%ld  reason为：%ld",(long)status,(long)reason);
    if(status == SERVER_STATUS_STOP_SHARE){
        [self changeUI];
    }
    else if(status == SERVER_STATUS_DISCONNECT){
        if(isSharing == YES){
            [self changeUI];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self->_meetControlBtn.enabled = NO;
            self->_shareControlBtn.enabled = NO;
            isConnected = NO;
            // 切换按钮样式
            [self->_connectBtn setTitle:@"开始连接" forState:UIControlStateNormal];
            self->_connectBtn.backgroundColor = [UIColor whiteColor];
            // 移除已连接设备
            [self->_deviceNameLbl removeFromSuperview];
        });
    }
}
- (void) onDevConfStatusChangeNotify : (IDEA_SHARE_APP_CONF_STATUS) confStatus : (IDEA_SHARE_APP_AUX_STATUS) auxStatus{
    DDLogInfo(@"会议状态变化,confStatus: %ld inMeeting: %ld isSharing: %ld auxStatus: %ld",(long)confStatus,inMeeting,isSharing, (long)auxStatus);
    inMeeting = confStatus == 1 ? YES : NO;
    //通知会控页面
    [meetControlVC OnDevConfStatusChangeNotify:(int)confStatus];
}

- (void) onRemoteServiceStatusChangedNotify :(RemoteServiceStatus *) remoteServiceStatus :(int) changeCount{
    switch (changeCount) {
        case 1:
            //通知会控页面
            [meetControlVC OnRemoteChairManStatusNotify:remoteServiceStatus.isChairman];
            break;
        case 2:
            //通知会控页面
            [meetControlVC OnRemoteSpeakerStatusNotify:remoteServiceStatus.isSpeakerMute];
            break;
        case 4:
            //通知会控页面
            [meetControlVC OnRemoteSpeakerVolumeStatusNotify:remoteServiceStatus.volume];
            break;
        case 8:
            //通知会控页面
            [meetControlVC OnRemoteCameraStatusNotify:remoteServiceStatus.isCameraMute];
            break;
        case 16:
            //通知会控页面
            [meetControlVC OnRemoteMicStatusNotify:remoteServiceStatus.isMute];
            break;
        default:
            break;
    }
}

- (void) stopShare{
    [self changeUI];
    [_mShareController stopSharing:^(id t){}];
}

- (void) changeUI{
    isSharing = NO;
    CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFSTR("app_tell_extension_finished"), NULL,NULL, YES);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self->_shareControlBtn setTitle:@"共享屏幕" forState:UIControlStateNormal];
        self->_shareControlBtn.backgroundColor = [UIColor whiteColor];
    });
}

- (void) onErrorNotify : (IDEA_SHARE_APP_ERR) errCode{
    DDLogInfo(@"收到错误事件，错误码为：%ld",(long)errCode);
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *errAlterControl = [UIAlertController alertControllerWithTitle:@"上报错误" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){}];
        //如果是ipad需要增加错误弹窗
        if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
            UIPopoverPresentationController *pop = [errAlterControl popoverPresentationController];
            pop.sourceView = self.view;//悬挂的视图
            pop.permittedArrowDirections = UIPopoverArrowDirectionUp;//箭头方向
            pop.sourceRect = self.view.bounds;//悬挂的地方
        }
        switch (errCode) {
            case PROJECTION_CODE_ERROR:{
                DDLogInfo(@"投屏码输入错误！！！");
                errAlterControl.title = @"连接失败";
                errAlterControl.message = @"投影码错误,请重新输入";
                break;
            }
            case CLIENT_IS_LOCKED_ERROR:{
                DDLogInfo(@"客户端被锁定！！！");
                errAlterControl.title = @"连接失败";
                errAlterControl.message = @"客户端被锁定，请稍后再试";
                break;
            }
            case AUTH_ERROR:{
                DDLogInfo(@"鉴权失败！！！ ");
                errAlterControl.title = @"连接失败";
                errAlterControl.message = @"投屏码过期或网络问题导致鉴权失败";
                break;
            }
            case CONNECT_ERROR:{
                DDLogInfo(@"连接失败！！！ ");
                errAlterControl.title = @"连接失败";
                errAlterControl.message = @"投屏码错误或网络问题导致连接失败";
                if(isConnected == YES){
                    // 切换连接按钮样式
                    [self->_connectBtn setTitle:@"开始连接" forState:UIControlStateNormal];
                    self->_connectBtn.backgroundColor = [UIColor whiteColor];
                    // 移除已连接设备
                    [self->_deviceNameLbl removeFromSuperview];
                    isConnected = NO;
                    // 投屏中停止投屏
                    if(isSharing == YES){
                        DDLogInfo(@"连接中断，停止投屏！！！");
                        [self stopShare];
                    }
                }
                break;
            }
            case CONF_NO_DATA_CAP_ERROR:{
                DDLogInfo(@"共享失败！！！ ");
                errAlterControl.title = @"共享失败";
                errAlterControl.message = @"当前会议不支持演示";
                break;
            }
            default:
                errAlterControl.message = [[NSString alloc]initWithFormat:@"错误码：%ld",(long)errCode];
                break;
        }
        
        [errAlterControl addAction:defaultAction];
        [self presentViewController:errAlterControl animated:YES completion:^{
                    self->_projectionNum.text = @"";
                    self->_projectionIP.text = @"";
                    self->_projectionPort.text = @"";
        }];
    });
}

-(BOOL)hasChineese:(NSString *)str{
    for(int i=0;i<str.length;i++){
        int a = [str characterAtIndex:i];
        if(a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}

+ (void)finishProjection{
    if(isSharing == YES){
        DDLogInfo(@"停止投屏！！！！");
        [selfClass -> _mShareController destroy];
        CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFSTR("app_tell_extension_finished"), NULL,NULL, YES);
        isSharing = NO;
        dispatch_async(dispatch_get_main_queue(), ^{
            [selfClass->_shareControlBtn setTitle:@"共享屏幕" forState:UIControlStateNormal];
            selfClass->_shareControlBtn.backgroundColor = [UIColor whiteColor];
        });
    }
}

- (void)audioRouteChangeCallBack:(NSNotification *)notification {
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger headSetChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (headSetChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            DDLogInfo(@"收到耳机状态变化事件：%ld",headSetChangeReason);
            if(isSharing == YES){
                [self stopShare];
            }
            break;
        default:
            DDLogInfo(@"收到耳机状态变化事件：%ld",headSetChangeReason);
    }
}

@end
